package com.atguigu.petstore.sys.minio.component.impl;

import com.atguigu.petstore.common.util.DateUtil;
import com.atguigu.petstore.sys.minio.component.FileUploadComponent;
import com.atguigu.petstore.sys.minio.config.properties.MinioProperties;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

/**
 * @author lfy
 * @Description
 * @create 2023-09-23 9:05
 */
@Component
public class FileUploadComponentImpl implements FileUploadComponent {

    @Autowired
    MinioClient minioClient;

    @Autowired
    MinioProperties minioProperties;
    @Override
    public String upload(MultipartFile file) throws Exception {

        //上传的文件的内容类型
        String contentType = file.getContentType();
        InputStream stream = file.getInputStream();

        //所有文件，以日期归档
        String date = DateUtil.formatDate(new Date(),"yyyy/MM/dd");
        String filename = date+"/"+ UUID.randomUUID().toString() + "_" + file.getOriginalFilename();


        PutObjectArgs args = PutObjectArgs.builder()
                .contentType(contentType) //内容类型
                .bucket(minioProperties.getBucket()) //哪个桶
                .stream(stream, stream.available(), -1L) //文件流
                .object(filename) //对象名字
                .build();


        //上传
        minioClient.putObject(args);//web应用上传


        //返回访问路径
        String path = minioProperties.getEndpoint()+"/"+minioProperties.getBucket()+"/"+filename;

        return path;
    }
}
